<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\index\BaseController;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;
use app\index\model\Message as MessageModel;
use app\common\validate\Message as MessageValidate;

class Message extends BaseController
{
    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['save']],
        'access:@' => ['only'=>['create','save']],
    ];

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return view('create',[
            'crumb' => [
                'home'=>'/',
                '联系' => request()->url()
            ]
        ]);
    }

    /**
     * 保存新建的资
     * @return \think\Response
     */
    public function save()
    {
        try{
            //验证数据
            $data = request()->only(['name','email','title','message']);

            validate(MessageValidate::class)->check($data);

            if( $this->getModel(MessageModel::class)->save($data) === false)
                throw new Exception('留言失败.');

            return json([
                'code' => 0,
                'msg' => '留言成功.'
            ]);


        } catch (ValidateException $e) {

            //验证错误
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        } catch (\Exception $e){

            //系统错误
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
    }


}
